package com.nl.strings;

public class ReplaceBlank {

	
	/**
	 * 替换字符串中的空格为20%<br>
	 * 两个指针，从后替换，减少字符移动次数，复杂度O(N)
	 * @param string
	 * @return
	 */
	static char[] replaceBlank(char[] string){
		if(string == null || string.length==0){
			return string;
		}

		int numberOfBlank = 0;
		for(int i=0,len= string.length;i<len;i++){
			if(string[i]== ' '){
				numberOfBlank++;
			}
		}
		if(numberOfBlank==0){
			return string;
		}

		int newLength = string.length + numberOfBlank*2;
		int lastIndex = string.length-1;
		int lastIndex2=newLength-1;
		char[] newString = new char[newLength];
		System.arraycopy(string, 0, newString, 0, string.length);
		while(lastIndex!=0&&lastIndex!=lastIndex2){
			if(newString[lastIndex]==' '){
				newString[lastIndex2--]='0';
				newString[lastIndex2--]='2';
				newString[lastIndex2--]='%';
			}else{
				newString[lastIndex2--] =newString[lastIndex];
			}
			lastIndex--;
		}
		return newString;
	}

	public static void main(String[] args) {
		char[] str =new char[]{'h','e','l','l','o',' ','w',' ','d'};
		char[] newStr = replaceBlank(str);
		System.out.println(new String(newStr));
	}
}
